package ArrayList;

import java.util.HashMap;

/**
 * @Classname JZ57和为s的两个数字
 * @Description TODO
 * @Date 2022/12/8 16:01
 * @Created by xjl
 */
public class JZ57和为s的两个数字 {

    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> map=new HashMap<>();
        for (int i=0;i<nums.length;i++){
            if (!map.containsKey(target-nums[i])){
                map.put(nums[i],i);
            }else {
                return new int[]{nums[i],target-nums[i]};
            }
        }
        return new int[]{};
    }

    /**
     * @description 使用有序的数组的特点来是实现
      * @param: nums
     * @param: target
     * @date: 2022/12/8 16:12
     * @return: int[]
     * @author: xjl
    */
    public int[] twoSum2(int[] nums, int target) {
        int left=0;
        int right=nums.length-1;
        while (left<right){
            int sum=nums[left]+nums[right];
            if (sum==target){
                return new int[]{nums[left],nums[right]};
            }else if (sum<target){
                left++;
            }else {
                right--;
            }
        }
        return new int[]{};
    }
}
